package com.tsj.model.utils;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.PackageRelationshipCollection;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author taoshujian
 * @version 1.0
 * @since 2025-10-24 15:34:41
 */
public class XlsxAttachmentExtractor {
    public static void main1(String[] args) {
        String filePath = "S://1.xlsx";
        try (XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(filePath))) {
            // 获取所有附件关联关系（附件属于 workbook 的关联资源）
            PackageRelationshipCollection relationships = workbook.getPackagePart().getRelationships();

            for (PackageRelationship rel : relationships) {
                // 筛选附件类型（附件的关系类型固定为 "http://schemas.openxmlformats.org/package/2006/relationships/officeDocument/embeddedPackage"）
                if (rel.getRelationshipType().equals("http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet")) {
                    // 获取附件对应的 PackagePart
                    PackagePart part = workbook.getPackagePart().getRelatedPart(rel);

                    // 获取附件信息
                    String fileName = part.getPartName().getName(); // 附件路径（如 "/xl/embeddings/oleObject1.bin"）
                    String contentType = part.getContentType();     // 附件 MIME 类型

                    System.out.println("发现附件：" + fileName + "，类型：" + contentType);

                    // 读取附件内容（通过输入流获取字节数据）
                    try (InputStream is = part.getInputStream()) {
                        byte[] content = is.readAllBytes(); // 附件字节内容
                        // 处理内容（如保存到文件、解析等）
                        System.out.println("附件大小：" + content.length + " 字节");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws FileNotFoundException {

    }
}
